package com.example.springboot3demo.controller;

import com.example.springboot3demo.service.AuthService;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.jsonwebtoken.lang.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@ApiSupport(order = 1)
@Tag(name = "登录", description = "登录")
@RequestMapping("/auth")
@RestController
public class AuthController {

    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录获取JWT令牌: " +
            "在 调试 -> AfterScript 界面 输入：" +
            " ke.global.setHeader(\"Authorization\", \"Bearer \" + ke.response.data.token);" +
            "请求之后，刷新页面，避免每次都输入请求token")
    public Map<String, String> login(@RequestBody LoginRequest request) {
        try {
            log.info("用户登录请求: {}", request.username());
            String token = authService.authenticate(request.username(), request.password());
            log.info("用户 {} 登录成功", request.username());
            return Maps.of("token", token).build();
        } catch (AuthenticationException e) {
            log.error("用户 {} 登录失败: {}", request.username(), e.getMessage());
            return null;
        }
    }

    record LoginRequest(String username, String password){

    }

}

